import path from "node:path";
import { RunnerSpec, TaskHandler } from "../types";
import { resolvePath, ensureDir } from "../utils";
import { validateThreeLayerArchitecture } from "../../../tools/validator";
import { writeJsonFile } from "../../../tools/data-processor";

export const fieldnodeCoverageTask: TaskHandler = async (spec) => {
  if (!spec.schema?.fields || !spec.schema.edit || !spec.schema.preview) {
    throw new Error("schema.fields, schema.edit, schema.preview are required for fieldnode.coverage");
  }

  const report = await validateThreeLayerArchitecture(spec.component, {
    fieldsFile: resolvePath(spec.schema.fields),
    editFile: resolvePath(spec.schema.edit),
    previewFile: resolvePath(spec.schema.preview),
  });

  const outputRelative = spec.report?.path ?? path.join("analysis", `${spec.component}-fieldnode-coverage.json`);
  const outputPath = resolvePath(outputRelative);
  await ensureDir(path.dirname(outputPath));
  await writeJsonFile(outputPath, report);

  return {
    summary: `FieldNode coverage: edit ${report.coverage.fieldsToEdit}, preview ${report.coverage.fieldsToPreview}`,
    outputPaths: { coverage: outputRelative },
    data: { report },
  };
};
